import React, { Component } from 'react'
import PubSub from 'pubsub-js';
import axios from 'axios';

export default class Content extends Component {

    state = {
        users: [],
        isSending: false, //是否正在发送请求...
    }

    render() {
        return (
            <div className="row">
                {this.state.isSending && <h3>正在获取中....</h3>}
                {
                    this.state.users.map(item => {
                        return <div key={item.login} className="card">
                            <a rel="noreferrer" href={item.html_url} target="_blank">
                                <img alt="" src={item.avatar_url} style={{ width: '100px' }} />
                            </a>
                            <p className="card-text">{item.login}</p>
                        </div>
                    })
                }

                {
                    (this.state.users.length === 0 && !this.state.isSending)   
                    ?   
                    <h3 className="empty">
                        没有相关的数据
                    </h3>
                    :  
                    null
                }
            </div>
        )
    }

    componentDidMount(){
        //订阅频道
        PubSub.subscribe('github', async (name, data) => {
            //提示 正在获取中....
            this.setState({
                isSending: true,
                users: []
            });

            //发送 AJAX 请求获取用户信息
            let result = await axios.get('https://api.github.com/search/users', {
                params: {
                    q: data.keyword
                }
            });

            this.setState({
                users: result.data.items,
                isSending: false
            })
        })
    }

    componentWillUnmount(){
        //组件销毁时, 取消订阅
        PubSub.unsubscribe('github');
    }

}
